<?php


namespace app\model;

use think\facade\Cache;
use think\facade\Db;
use think\response\Json;
use Exception;

class SchoolModel
{
    private static $_table = 'eb_school'; // 学校表
    private static $_adminTale = 'eb_admin'; // 管理员表

    /**列表
     * @param $input
     * @param $token
     * @return Json
     */
    public static function list($input, $token)
    {
        try {
            // 检测当前管理员状态
            $adminInfo = AdminModel::getInfo($token, [1], [1]);
            if ($adminInfo instanceof Json) return $adminInfo;
            $map = [];
            $field = 's.id,s.name,s.logo, FROM_UNIXTIME(s.create_time, "%Y-%m-%d %H:%i:%s") AS create_time, s.delivery, s.company,a.name as operate_name,s.type';
            if ($input['operate_id'] != '') $map[] = ['operate_id', '=', $input['operate_id']];
            $table = Db::table(self::$_table)->alias('s')
                ->leftJoin([self::$_adminTale => 'a'], 'a.id = s.operate_id')
                ->field($field)->where($map);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('获取成功', ['count' => 0, 'list' => []]);
            $list = $table->page($input['page'], $input['limit'])->order('s.create_time', 'desc')->select()->toArray();
            return jsonSuccess('获取成功！', ['count' => $count, 'list' => $list]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**添加
     * @param $input
     * @param $token
     * @return Json
     */
    public static function increase($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $rtn = AdminModel::getInfo($token, [1], [1]);
            if ($rtn instanceof Json) return $rtn;
            // 添加数据
            $input['create_time'] = time();
            $where = "not exists (select id from `" . self::$_table . "` where `name` = '{$input['name']}')";
            $input['delivery'] = '';
            $sql = makeDualSql(self::$_table, $input, $where);
            Db::startTrans();
            $flag = true;
            $rtn = Db::execute($sql);
            if ($rtn) {
                //添加缓存
                $data = [
                    'name' => $input['name'],
                    'operate_id' => $input['operate_id'],
                    'type' => $input['type'],
                    'company' => $input['company'],
                    'delivery' => '',
                    'allow_order' => 1
                ];
                $map = [
                    ['name', '=', $input['name']]
                ];
                $schoolId = Db::table(self::$_table)->field('id')->where($map)->find();
                if (!$schoolId) {
                    Db::rollback();
                    return jsonFail('添加失败！');
                }
                $addRtn = Cache::store('redis')->handler()->hMSet('dxsd-school-' . $schoolId['id'], $data);
                if ($addRtn === true) {
                    Db::commit();
                    return jsonSuccess('添加成功！');
                } else {
                    Db::rollback();
                    return jsonFail('添加失败！');
                }
            } else {
                Db::rollback();
                return jsonFail('该学校名已使用，添加失败！');
            }
        } catch (Exception $e) {
            var_dump($e->getMessage());
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**管理员获取自己管辖的学校列表
     * @param $input
     * @param $token
     * @return Json
     */
    public static function getOwnList($input, $token)
    {
        try {
            // 检测当前管理员状态
            $rtn = AdminModel::getInfo($token, [1], [2]);
            if ($rtn instanceof Json) return $rtn;
            // 获取列表
            $table = Db::table(self::$_table);
            $table->field('id, name,dor_manager_price,box_price,allow_order,is_go_up,FROM_UNIXTIME(create_time, "%Y-%m-%d %H:%i:%s") AS create_time');
            $map = [
                ['operate_id', '=', $rtn['id']]
            ];
            if ($input['name'] !== '') $map[] = ['name', 'like', "%{$input['name']}%"];
            $table->where($map);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('查询成功', ['count' => $count, 'list' => []]);
            $list = $table->order('create_time', 'desc')->page($input['page'], $input['limit'])->select();
            return jsonSuccess('查询成功', ['count' => $count, 'list' => $list]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**管理员获取自己管辖的学校划账费用信息
     * @param $input
     * @param $token
     * @return Json
     */
    public static function getDrawInfo($input, $token)
    {
        try {
            // 检测当前管理员状态
            $rtn = AdminModel::getInfo($token, [1], [2]);
            if ($rtn instanceof Json) return $rtn;
            // 获取列表
            $table = Db::table(self::$_table);
            $table->field('id, dor_manager_price,box_price');
            $map = [
                ['id', '=', $input['id']],
                ['operate_id', '=', $rtn['id']]
            ];
            $table->where($map);
            $rtn = $table->find();
            return jsonSuccess('查询成功', $rtn);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**管理员编辑自己管辖的学校划账费用信息
     * @param $input
     * @param $token
     * @return Json
     */
    public static function editDraw($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $rtn = AdminModel::getInfo($token, [1], [2]);
            if ($rtn instanceof Json) return $rtn;
            $map = [
                ['id', '=', $input['id']],
                ['operate_id', '=', $rtn['id']]
            ];
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_table)->where($map)->update($input);
            if (!$rtn) {
                Db::rollback();
                return jsonFail('数据未更改编辑失败');
            }
            // 更新缓存
            $id = $input['id'];
            unset($input['id']);
            $editRtn = Cache::store('redis')->handler()->hMSet('dxsd-school-' . $id, $input);
            if ($editRtn === true) {
                Db::commit();
                return jsonSuccess('编辑成功！');
            } else {
                Db::rollback();
                return jsonFail('编辑失败！');
            }
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**获取单个
     * @param $input
     * @param $token
     * @return Json
     */
    public static function getOnly($input, $token)
    {
        try {
            // 检测当前管理员状态
            $rtn = AdminModel::getInfo($token, [1], [1]);
            if ($rtn instanceof Json) return $rtn;
            $map = [
                ['id', '=', $input['id']]
            ];
            $field = 'id,operate_id,name,logo,delivery,company,type';
            $data = Db::table(self::$_table)->field($field)->where($map)->find();
            if ($data) return jsonSuccess('获取成功！', $data);
            return jsonFail('未找到学校信息');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**编辑
     * @param $input
     * @param $token
     * @return Json
     */
    public static function edit($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $rtn = AdminModel::getInfo($token, [1], [1]);
            if ($rtn instanceof Json) return $rtn;
            $map = [
                ['id', '=', $input['id']],
            ];
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_table)->where($map)->update($input);
            if ($rtn) {
                // 更新缓存
                $data = [
                    'name' => $input['name'],
                    'operate_id' => $input['operate_id'],
                    'type' => $input['type'],
                    'company' => $input['company'],
                ];
                $editRtn = Cache::store('redis')->handler()->hMSet('dxsd-school-' . $input['id'], $data);
                if ($editRtn === true) {
                    Db::commit();
                    return jsonSuccess('编辑成功！');
                } else {
                    Db::rollback();
                    return jsonFail('编辑失败！');
                }
            } else {
                Db::rollback();
                return jsonFail('数据未更改编辑失败');
            }
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**学校允许下单
     * @param $input
     * @param $token
     * @return Json
     */
    public static function changeAllowOrder($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $rtn = AdminModel::getInfo($token, [1], [2]);
            if ($rtn instanceof Json) return $rtn;
            $map = [
                ['id', '=', $input['id']],
            ];
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_table)->where($map)->update($input);
            if ($rtn) {
                // 更新缓存
                $data = [
                    'allow_order' => $input['allow_order']
                ];
                $editRtn = Cache::store('redis')->handler()->hMSet('dxsd-school-' . $input['id'], $data);
                if ($editRtn === true) {
                    Db::commit();
                    return jsonSuccess('编辑成功！');
                } else {
                    Db::rollback();
                    return jsonFail('编辑失败！');
                }
            } else {
                Db::rollback();
                return jsonFail('数据未更改编辑失败');
            }
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**学校允许上楼
     * @param $input
     * @param $token
     * @return Json
     */
    public static function changeGoUp($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $rtn = AdminModel::getInfo($token, [1], [2]);
            if ($rtn instanceof Json) return $rtn;
            $map = [
                ['id', '=', $input['id']],
            ];
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_table)->where($map)->update($input);
            if ($rtn) {
                // 更新缓存
                $data = [
                    'is_go_up' => $input['is_go_up']
                ];
                $editRtn = Cache::store('redis')->handler()->hMSet('dxsd-school-' . $input['id'], $data);
                if ($editRtn === true) {
                    Db::commit();
                    return jsonSuccess('编辑成功！');
                } else {
                    Db::rollback();
                    return jsonFail('编辑失败！');
                }
            } else {
                Db::rollback();
                return jsonFail('数据未更改编辑失败');
            }
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }
    /**删除
     * @param $input
     * @param $token
     * @return Json
     */
    public static function delete($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $rtn = AdminModel::getInfo($token, [1], [1]);
            if ($rtn instanceof Json) return $rtn;
            $map = [
                ['id', '=', $input['id']]
            ];
            Db::startTrans();
            $flag = true;
            $res = Db::table('eb_school')->where($map)->delete();
            if ($res) {
                // 删除缓存
                $delRtn = Cache::store('redis')->handler()->del('dxsd-school-' . $input['id']);
                if ($delRtn === 1) {
                    Db::commit();
                    return jsonSuccess('删除成功！');
                } else {
                    Db::rollback();
                    return jsonFail('删除失败！');
                }
            } else {
                Db::rollback();
                return jsonFail('删除失败');
            }
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**费用设置列表
     * @param $input
     * @param $token
     * @return Json
     */
    public static function deliveryList($input, $token)
    {
        try {
            // 检测当前管理员状态
            $adminInfo = AdminModel::getInfo($token, [1], [2]);
            if ($adminInfo instanceof Json) return $adminInfo;
            $map[] = ['id', '=', $input['school_id']];
            $map[] = ['operate_id', '=', $adminInfo['id']];
            $field = 'id,delivery';
            $list = Db::table(self::$_table)->field($field)->where($map)->find();
            if (!$list) return jsonFail('未找到数据');
            return jsonSuccess('获取成功！', $list);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**费用设置
     * @param $input
     * @param $token
     * @return Json
     */
    public static function editDelivery($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $rtn = AdminModel::getInfo($token, [1], [2]);
            if ($rtn instanceof Json) return $rtn;
            $map = [
                ['id', '=', $input['id']],
            ];
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_table)->where($map)->update($input);
            if ($rtn) {
                // 更新缓存
                $editRtn = Cache::store('redis')->handler()->hSet('dxsd-school-' . $input['id'], 'delivery', $input['delivery']);
                if ($editRtn === 0) {
                    Db::commit();
                    return jsonSuccess('编辑成功！');
                } else {
                    Db::rollback();
                    return jsonFail('编辑失败！');
                }
            } else {
                Db::rollback();
                return jsonFail('数据未更改编辑失败');
            }
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }
}